package com.mall.auth_server.controller;

import com.alibaba.fastjson.JSON;
import com.common.constants.AuthConstant;
import com.common.exception.BizCodeEnums;
import com.common.utils.R;
import com.common.vo.MemberVo;
import com.mall.auth_server.constants.SMSConstants;
import com.mall.auth_server.feign.MemberFeignService;
import com.mall.auth_server.feign.ThirdPartFeignService;
//import com.mall.auth_server.utils.SmsComponent;
import com.mall.auth_server.vo.LoginVo;
import com.mall.auth_server.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.crypto.agreement.srp.SRP6Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {
//    @Autowired
//    SmsComponent smsComponent;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("/sms/sms/sendCode")
    @ResponseBody
    public R sendSmsCode(@RequestParam("phone") String phone){
        String redisCode = stringRedisTemplate.opsForValue().get(SMSConstants.SMS_CODE_PERFIX + phone);
        if(StringUtils.isNotBlank(redisCode)){
            long split = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - split <= 60000){
                return R.error(BizCodeEnums.VALID_SMS_EXCEPTION.getCode(),BizCodeEnums.VALID_SMS_EXCEPTION.getMsg());
            }
        }
        String code = "1234" + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(SMSConstants.SMS_CODE_PERFIX + phone,code,60, TimeUnit.SECONDS);
//        smsComponent.sendSmsCode(phone,code);
        return R.ok();
    }
    @PostMapping("/sms/register")
    public String Register(@Valid UserRegisterVo vo, BindingResult result, Model model){
        Map<String,String > map = new HashMap<>();
        if (result.hasErrors()){
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError error : errors) {
                String field = error.getField();
                String message = error.getDefaultMessage();
                map.put(field,message);
            }
            model.addAttribute("error",map);
            return "/reg";
        }else {
            String code = stringRedisTemplate.opsForValue().get(SMSConstants.SMS_CODE_PERFIX + vo.getPhone(), 0, 100);
            assert code != null;
            if (!Objects.equals(code.split("_")[0], vo.getCode())){
                map.put("code","验证码错误");
                model.addAttribute("error",map);
            }else {
                stringRedisTemplate.delete(SMSConstants.SMS_CODE_PERFIX + vo.getPhone());
                R r = memberFeignService.register(vo);
                System.out.println("------->会员注册完成");
                if (r.getCode() == 0){
                    return "redirect:http://auth.msb.com/login.html";
                }else {
                    map.put("msg","注册失败，手机或者账号重复");
                    model.addAttribute("error",map);
                    return "/reg";
                }
                //远程调用

            }
        }
        return "redirect:http://auth.msb.com/login.html";
    }
    /**
     * 注册的方法
     * @return
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo ,
                        HttpSession session){
        R r = memberFeignService.login(loginVo);
        if(r.getCode() == 0){
            String entityJson = (String) r.get("entity");
            MemberVo memberVO = JSON.parseObject(entityJson, MemberVo.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            // 表示登录成功
            return "redirect:http://mall.msb.com/home";
        }

        session.setAttribute("errors",r.get("msg"));

        // 表示登录失败,重新跳转到登录页面
        return "redirect:http://auth.msb.com/login.html";
    }
}

